<template>
  <!-- 工作组及对应结果 -->
  <div id="wL">
    <Splitpanes>
      <Pane size="65">
        <vxe-table ref="wLTable" border resizable show-overflow height="auto" :data="wL" :row-config="{ isCurrent: true, isHover: true }" :keyboard-config="{ isArrow: true }" :sort-config="{ trigger: 'cell' }" :cell-class-name="cellClassName" @current-change="wLRowClick">
          <vxe-column field="isEmergency" width="16" fixed="left">
            <template #header>
              <span style="font-size: 7px; font-weight: 150">急</span>
            </template>
            <template #default="{ row }">
              <span v-if="row.isEmergency" class="el-icon-first-aid-kit"></span>
            </template>
          </vxe-column>
          <vxe-column field="isPrinted" width="16" fixed="left">
            <template #header>
              <span style="font-size: 7px; font-weight: 150">打</span>
            </template>
            <template #default="{ row }">
              <i v-if="row.isPrinted" class="el-icon-printer"></i>
            </template>
          </vxe-column>
          <vxe-column field="isCarmPrinted" width="16" fixed="left">
            <template #header>
              <span style="font-size: 7px; font-weight: 150">自</span>
            </template>
            <template #default="{ row }">
              <i v-if="row.isCarmPrinted" class="el-icon-s-platform"></i>
            </template>
          </vxe-column>
          <vxe-column field="isReviewed" width="16" fixed="left">
            <template #header>
              <span style="font-size: 7px; font-weight: 150">审</span>
            </template>
            <template #default="{ row }">
              <i v-if="row.isReviewed" class="el-icon-finished"></i>
            </template>
          </vxe-column>
          <vxe-column field="isCritical" width="16" fixed="left">
            <template #header>
              <span style="font-size: 7px; font-weight: 150">危</span>
            </template>
            <template #default="{ row }">
              <i v-if="row.isCritical" class="el-icon-warning"></i>
            </template>
          </vxe-column>
          <vxe-column field="code" title="标本号" width="57" sortable fixed="left">
            <template #default="{ row }">
              <span :style="{ color: row.displayColor }">{{ row.code }}</span>
            </template>
          </vxe-column>
          <vxe-column field="specCode" title="条码号" width="90" sortable fixed="left">
            <template #default="{ row }">
              <span :style="{ color: row.displayColor }">{{ row.specCode }}</span>
            </template>
          </vxe-column>
          <vxe-column field="fullName" title="姓名" width="70" sortable fixed="left">
            <template #default="{ row }">
              <span :style="{ color: row.displayColor }">{{ row.fullName }}</span>
            </template>
          </vxe-column>
          <vxe-column field="medicalRecNo" title="病历号" width="128" fixed="left">
            <template #default="{ row }">
              <span :style="{ color: row.displayColor }">{{ row.medicalRecNo }}</span>
            </template>
          </vxe-column>
          <vxe-column field="visitTypeName" title="类型" width="50" sortable>
            <template #default="{ row }">
              <span :style="{ color: row.displayColor }">{{ row.visitTypeName }}</span>
            </template>
          </vxe-column>
          <vxe-column field="patDepName" title="科室" width="70" show-overflow></vxe-column>
          <vxe-column field="sex" title="性别" width="35" show-overflow></vxe-column>
          <vxe-column field="medicalRecAge" title="年龄" width="50" show-overflow></vxe-column>
          <vxe-column field="applicationItems" title="检验目的" width="170" show-overflow></vxe-column>
          <vxe-column field="bedCode" title="床号" width="60" show-overflow></vxe-column>
          <vxe-column field="specTypeName" title="样本类型" min-width="100" show-overflow></vxe-column>
        </vxe-table>
      </Pane>
      <Pane size="35">
        <vxe-table ref="wLResultTable" border resizable show-overflow height="auto" v-loading="loading" :data="wLResultList" :row-config="{ isCurrent: true, isHover: true }" :keyboard-config="{ isArrow: true }">
          <vxe-column field="exaItem" title="检验项目" width="120">
            <template #default="{ row }">
              <span :style="{
                  color: row.exaCriticalValueLevel ? row.exaCriticalValueLevel.displayColor : ''
                }">{{ row.exaItem.name }}{{ row.exaItem ? '(' + row.exaItem.unit + ')' : '' }}
              </span>
            </template>
          </vxe-column>
          <vxe-column field="result" title="结果" width="80">
            <template #default="{ row }">
              <span :style="{
                  color: row.exaResultStatus ? row.exaResultStatus.displayColor : ''
                }">
                {{ row.result }}
              </span>
            </template>
          </vxe-column>
          <vxe-column width="30">
            <template #default="{ row }">
              <span :style="{
                  color: row.exaResultStatus ? row.exaResultStatus.displayColor : '',
                  position: 'relative',
                  top: '-2px',
                  display: 'inline-block',
                  width: '14px'
                }">
                {{ row.exaResultStatus ? '&nbsp;' + row.exaResultStatus.displayFlag : '' }}
              </span>

              <el-tooltip v-if="row.ansCriticalValue && row.ansCriticalValue.instruction" class="item" effect="dark" :content="row.ansCriticalValue.instruction" placement="top">
                <span :style="{
                    color: row.exaCriticalValueLevel ? row.exaCriticalValueLevel.displayColor : '',
                    position: 'relative',
                    top: '-2px'
                  }">
                  {{ row.exaCriticalValueLevel ? row.exaCriticalValueLevel.displayFlag : '' }}</span>
              </el-tooltip>

              <span v-else :style="{
                  color: row.exaCriticalValueLevel ? row.exaCriticalValueLevel.displayColor : '',
                  position: 'relative',
                  top: '-2px'
                }">{{ row.exaCriticalValueLevel ? row.exaCriticalValueLevel.displayFlag : '' }}</span>
            </template>
          </vxe-column>
          <vxe-column field="referenceRange" title="参考范围" min-width="60">
            <template #default="{ row }">
              <el-tooltip v-if="row.ansReferenceRange && row.ansReferenceRange.referenceRangeInstruction" class="item" effect="dark" :content="row.ansReferenceRange.referenceRangeInstruction" placement="top">
                <span> {{ row.referenceRange }}</span>
              </el-tooltip>
              <span v-else>{{ row.referenceRange }}</span>
            </template>
          </vxe-column>
        </vxe-table>
      </Pane>
    </Splitpanes>
  </div>
</template>
<script lang="ts" setup>
import { reactive, ref, getCurrentInstance } from 'vue';
import { VXETable } from 'vxe-table';
import type { VxeTableInstance, VxeTablePropTypes, VxeTableEvents } from 'vxe-table';
import XEClipboard from 'xe-clipboard';
import { IsEmpty, formatDateTime } from '@/utils/common';
import VxePulldownSelection from '@/components/VxePulldownSelection.vue';
import { Splitpanes, Pane } from 'splitpanes';
import MainInfoEditPanel from '@/components/MainInfoEditPanel.vue';
import RptResult from './components/RptResult.vue';
import TestList from './components/TestList.vue';
import { Jh_timeStampToTime } from '@/utils/TimeUtils';
import { VxeMessage, VxeNotifyType } from '../../../../utils/CommonMessage';
let { proxy }: any = getCurrentInstance();
const WLloading = ref(false);
const loading = ref(false);
let wL: any = reactive([]);
let wLResultList: any = reactive([]); //检验结果
let filtervisitTypeName: any = reactive([]); //工作组中病人类型过滤条件
let wfilterpatDepNameL: any = reactive([]);
let filtersex: any = reactive([]);
let filterspecTypeName: any = reactive([]);
let currentWkltRow: any = reactive([]);

let form: any = reactive({});

// 获取工作列表
function getWklt(formr) {
  form = formr;
  if (IsEmpty(form.selectWtId)) {
    wLResultList.length = 0;
    VxeMessage('请选择工作组', VxeNotifyType.warning);
    return;
  }
  WLloading.value = true;
  const url = '/api/lims/work-lists-views/get-list-pages';
  const data = {
    wtId: form.selectWtId,
    scheduleDate_Begin: formatDateTime(form.scheduleDate, 'yyyy-MM-dd') + ' 00:00:00',
    scheduleDate_end: formatDateTime(form.scheduleDate, 'yyyy-MM-dd') + ' 23:59:59',
    visitTypeIds: form.visitTypeIds,
    specTypeIds: form.specTypeIds,
    code: form.code,
    isReviewed: IsEmpty(form.isReviewed) ? null : form.isReviewed, //是否审核
    isPrinted: IsEmpty(form.isPrinted) ? null : form.isPrinted, //是否打印
    isFilterNoResult: form.isFilterNoResult, //根据结果筛选
    isFilterNoSpecCode: form.isFilterNoSpecCode, //根据条码号筛选
    isFilterNoPatName: form.isFilterNoPatName, //根据病人姓名筛选
    customSorting: form.customSorting, //打印顺序
    skipCount: 0,
    maxResultCount: 500
  };
  proxy.$http
    .post(url, data)
    .then((res: any) => {
      wL = res.items;
      // 获取筛查条件数组
      getFilterColumn('visitTypeName');
      getFilterColumn('patDepName');
      getFilterColumn('sex');
      getFilterColumn('specTypeName');

      wLRowClick({ row: wL[0] });

      WLloading.value = false;
    })
    .catch((err) => {
      loading.value = false;
      VxeMessage(err.data.error.message, VxeNotifyType.error);
    });
}

// 行点击事件
function wLRowClick({ row }) {
  if (IsEmpty(row)) {
    wLResultList = [];
    return;
  }
  // ($refs.wLTable as any).setCurrentRow(row);
  currentWkltRow = row;
  getWkltResultList();
}

// 获取检验结果
function getWkltResultList() {
  loading.value = true;
  const url = '/api/lims/work-list-results/all';
  const data = {
    wlId: currentWkltRow.id
  };
  proxy.$http
    .get(url, { params: data })
    .then((res: any) => {
      wLResultList = res.items;
      loading.value = false;
    })
    .catch((err) => {
      loading.value = false;
      VxeMessage(err.data.error.message, VxeNotifyType.error);
    });
}

// 表头操作
function renderHeader(h, data) {
  return h('span', [
    h(
      'el-tooltip',
      {
        attrs: {
          class: 'item',
          effect: 'dark',
          content: data.column.label,
          placement: 'bottom'
        }
      },
      [h('span', data.column.label)]
    )
  ]);
}

// 获取筛查条件数组
function getFilterColumn(name) {
  this['filter' + name] = [];
  wL.forEach((item, index) => {
    if (!IsEmpty(item[name])) {
      if (index === 0) {
        this['filter' + name].push({
          text: item[name],
          value: item[name]
        });
      } else {
        const isHave = this['filter' + name].some((val) => {
          return val.text === item[name];
        });
        if (!isHave) {
          this['filter' + name].push({
            text: item[name],
            value: item[name]
          });
        }
      }
    }
  });
}
// 设置筛查条件
function setFilterColumn(value, row, name) {
  return row[name] === value;
}

function cellClassName({ row, rowIndex, column, columnIndex }) {
  if (column.property === 'isEmergency') {
    if (row.isEmergency === true) {
      return 'bg-red';
    } else {
      return '';
    }
  }
  if (column.property === 'isReviewed') {
    if (row.isReviewed === true) {
      return 'bg-blue';
    } else {
      return '';
    }
  }
  if (column.property === 'isCritical') {
    if (row.isCritical === true) {
      return 'bg-orange';
    } else {
      return '';
    }
  }
  if (column.property === 'isCarmPrinted') {
    if (row.isCarmPrinted === true) {
      return 'bg-green';
    } else {
      return '';
    }
  }
  if (column.property === 'isPrinted') {
    if (row.isPrinted === true) {
      return 'bg-pink';
    } else {
      return '';
    }
  }
}

// #region 【列排序】
// 列排序 a和b 就是表格数据（a是第一条b是第二条，a是第三条b是第四条 以此类推）
function sortColumn(a, b, key) {
  let res = 0;
  // 如果两个数据中有为空的值
  if (IsEmpty(a[key])) {
    return -1;
  } else if (IsEmpty(b[key])) {
    return 1;
  }
  for (let i = 0; ; i++) {
    if (!a[key][i] || !b[key][i]) {
      res = a[key].length - b[key].length;
      break;
    }
    const char1 = a[key][i];
    const char1Type: any = getChartType(char1);
    const char2 = b[key][i];
    const char2Type: any = getChartType(char2);
    // 类型相同的逐个比较字符
    if (char1Type[0] === char2Type[0]) {
      if (char1 === char2) {
        continue;
      } else {
        if (char1Type[0] === 'zh') {
          res = char1.localeCompare(char2);
        } else if (char1Type[0] === 'en') {
          res = char1.charCodeAt(0) - char2.charCodeAt(0);
        } else {
          res = char1 - char2;
        }
        break;
      }
    } else {
      // 类型不同的，直接用返回的数字相减
      res = char1Type[1] - char2Type[1];
      break;
    }
  }
  return res;
}
// 排序，数字->大写字母->小写字母->中文拼音
function getChartType(val) {
  if (/^[\u4e00-\u9fa5]$/.test(val)) {
    return ['zh', 300];
  }
  if (/^[a-zA-Z]$/.test(val)) {
    return ['en', 200];
  }
  if (/^[0-9]$/.test(val)) {
    return ['number', 100];
  }
  return ['others', 999];
}
</script>
<style lang="scss" scoped>
#wL {
  height: 100%;
  :deep(.el-table) {
    td,
    th {
      padding: 2px;
    }
    th > .cell,
    td > .cell {
      padding: 0;
      word-break: keep-all;
      white-space: nowrap;
    }
    // 排序箭头
    .caret-wrapper {
      height: 23px;
      .sort-caret.ascending {
        top: 1px;
      }
      .sort-caret.descending {
        bottom: 1px;
      }
    }
    .cell.el-tooltip {
      min-width: 0;
      padding: 0 2px;
      // 急诊
      .isEmergency {
        color: $danger-color;
      }
      // 初审
      .isFirstReviewed {
        color: $warning-color;
      }
      // 审核
      .isReviewed {
        color: $brand-color;
      }
      // 完成
      .el-icon-circle-check {
        color: $success-color;
      }
      // 危急
      .isCritical {
        color: $danger-color;
      }
    }
    .table-icon {
      padding: 0;
      .cell.el-tooltip {
        padding: 0;
        i {
          font-size: 12px;
          font-weight: 700;
        }
      }
    }
    .ultra-small-font {
      font-weight: 500;
      font-size: 12px;
      line-height: 12px;
      transform: scale(0.9);
    }
  }
  :deep(.el-table__column-filter-trigger) {
    line-height: 23px;
  }
}
</style>
